package com.github.xiaoy.aop;

import com.github.xiaoy.DataSource;
import com.github.xiaoy.MultiDbConnectionConfig;
import lombok.NonNull;
import lombok.SneakyThrows;
import org.aopalliance.aop.Advice;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.PointcutPrimitive;
import org.springframework.aop.Pointcut;

import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.ComposablePointcut;
import org.springframework.aop.support.NameMatchMethodPointcut;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.lang.annotation.Annotation;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TaoYu
 * @since 1.2.0
 */
public class DynamicDataSourceAnnotationAdvisor extends AbstractPointcutAdvisor implements
        BeanFactoryAware {

    private Advice advice;

    private Pointcut pointcut;

    private DynamicDataSourceAnnotationInterceptor dynamicDataSourceAnnotationInterceptor;

    private static final MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();

    private static final Environment environment = new StandardEnvironment();

    private static final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    public DynamicDataSourceAnnotationAdvisor(@NonNull DynamicDataSourceAnnotationInterceptor interceptor) {
        this.advice = interceptor;
        this.dynamicDataSourceAnnotationInterceptor = interceptor;
        this.pointcut = buildPointcut();
    }

    @Override
    public Pointcut getPointcut() {
        return this.pointcut;
    }

    @Override
    public Advice getAdvice() {
        return this.advice;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        if (this.advice instanceof BeanFactoryAware) {
            ((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);
        }
    }

    private Pointcut buildPointcut() {
      NameMatchMethodPointcutCustom nameMatchMethodPointcut = new NameMatchMethodPointcutCustom();
        List<String> pathList = this.dynamicDataSourceAnnotationInterceptor.getDbConnConfig().getList()
                .stream()
                .map(MultiDbConnectionConfig.ConnectionInfo::getLocation).collect(Collectors.toList());
        List<List<Class<?>>> collect = pathList.stream().map(it -> {
            return getClassByPackage(it);
        }).collect(Collectors.toList());
        collect.forEach(it -> {
//            it.stream().map(clas -> {
//                return new AnnotationMatchingPointcut((Class<? extends Annotation>) clas, true);
//            });
            it.forEach(cla -> {
                nameMatchMethodPointcut.addMethodClassName(cla.getSimpleName());
            });
        });
      Pointcut pointcut = nameMatchMethodPointcut;
//      AspectJExpressionPointcut aspectJExpressionPointcut = new AspectJExpressionPointcut("execution(* service.HelloService.*(..))");

//      List<Pointcut> pointcutList = pathList.stream().map(path -> {
//        String execution = "execution(* " + path + "..*(..))";
//        Pointcut cpc = new AspectJExpressionPointcut(execution);
//        return cpc;
//      }).collect(Collectors.toList());
//      ComposablePointcut composablePointcut = new ComposablePointcut();
//      pointcutList.forEach(pointcut ->{
//        composablePointcut.union(pointcut);
//      });


//    Pointcut cpc = new AnnotationMatchingPointcut(DataSource.class, true);
//    Pointcut mpc = AnnotationMatchingPointcut.forMethodAnnotation(DataSource.class);
//    return new ComposablePointcut(nameMatchMethodPointcut).union(mpc);
      String execution = "execution(* " + "github.xiaoy.sample.mapper" + "..*(..))";
        return nameMatchMethodPointcut;
    }


    /**
     * 根据包路径找到所有的改包下面所有的class
     * 例org.recipe.draw.**.mapper与MapperScan注解的写法一致
     */
    @SneakyThrows
    public static List<Class<?>> getClassByPackage(String... pathArray) {
        Set<Class<?>> set = new HashSet<>();
        for (String path : pathArray) {
            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    resolveBasePackage(path) + '/' + "**/*.class";
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass(metadataReader.getClassMetadata().getClassName());
                    set.add(clazz);
                }
            }
        }
        return new ArrayList<>(set);
    }

    private static String resolveBasePackage(String basePackage) {
        return ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(basePackage));
    }


}
